'use strict';

const Service = require('egg').Service;

class GroupService extends Service {

    //1.关键词查找群
async search(keyword){
    let search=[];
    let nameResult=await this.app.model.Group.findAll( { where: { name: { $like: `%${keyword}%` } } } );//群名模糊查找 
    let idResult=await this.app.model.Group.findAll( { where: { id: { $like: `%${keyword}%` } } } );//群id查找
    search.push(...nameResult);
    search.push(...idResult);
    let groupResult =await this.unique(search,"id");//数组去重
    if(groupResult){
        return groupResult
    }else{
        return false
    }
}
//对象数组去重
async unique(arr, key) {
    if (!arr) return arr
    if (key === undefined) return [...new Set(arr)]
    const map = {
        'string': e => e[key],
        'function': e => key(e),
    }
    const fn = map[typeof key]
    const obj = arr.reduce((o,e) => (o[fn(e)]=e, o), {})
    return Object.values(obj)
}

//2. 判断自己是不是在群内
async isInGroup(user_id,group_id) {
    let judgeResult = await this.app.model.GroupMember.findOne({where:{user_id:user_id , group_id:group_id}});
    if(judgeResult){
        return{
            state:7,
            message:'已加入',
        }
    }else{
        return{
            state:8,
            message:'未加入'
        }
    }
}

//3. 获取群信息并判断自己是不是在群里
async groupDetail(user_id,group_id){
    let detailData=await this.app.model.Group.findOne({where:{id:group_id}});
    // if(detailData){
        let groupState=await this.isInGroup(user_id,group_id)
        return {
            detailData,
            groupState
        }
    ///   }else{
    //       return{
    //           code:400,
    //           message:'好友信息获取失败！'
         //   }
    //   }
    }

    async getGroupList(id){
        let ingroup=await this.app.model.GroupMember.findAll({where:{user_id:id}});
        //将检索到的对象中的group_id组成数组返回
        let groupIdList=[];
        for(let i of ingroup){
            groupIdList.push(i.group_id)
        }
        
        //检索全部群聊信息
        let groupLists=[];
        for(let i of groupIdList){
        let groupList= await this.app.model.Group.findOne({
            where:{id:i}
            })
            groupLists.push(groupList)
        }
        return {groupIdList,groupLists}     
    }

    //获取全部群成员信息
    async getGroupMembers(group_id){
        let getResult=await this.app.model.GroupMember.findAll({where:{group_id:group_id}});
        let groupMemberIds=[];
        for(let i of getResult){
         groupMemberIds.push(i.user_id);
        }
        let groupMembers=[];
        for(let i of groupMemberIds){
            let userDetail=await this.app.model.User.findOne({where:{id:i}})
            groupMembers.push(userDetail)
        }
        return groupMembers;
    }

    //建群
    async createGroup(user_id,groupinfo){
        let groupMessage={
            user_id:user_id,
            name:groupinfo.name,
            imgurl:groupinfo.imgurl,
            notice:groupinfo.notice,
            time:new Date(),
          };
         await this.app.model.Group.create(groupMessage);
         let creatingGroup=await this.app.model.Group.findOne({where:{user_id:user_id,name:groupinfo.name}});
         let creatingGroupId=creatingGroup.id;
         let loardMessage={
             group_id:creatingGroupId,
             user_id:user_id,
             time:new Date(),
             name:groupinfo.lordname,
             tip:1,
             lasttime:new Date(),
             shield:0
         }
         await this.app.model.GroupMember.create(loardMessage);
         let createGroupMessage={
             user_id:user_id,
             group_id:creatingGroupId,
             message:`${groupinfo.lordname}创建了群聊“${groupinfo.name}”！`,
             time:new Date(),
             types:0
         }
         await this.app.model.GroupMessage.create(createGroupMessage);
         return true
    }
    
    //加入群聊
    async applyGroup(user_id,group_id,name){
          let applyGroupData={
              group_id:group_id,
              user_id:user_id,
              name:name,
              time:new Date(),
              tip:1,
              lasttime:new Date(),
              shield:0,
          }
          await this.app.model.GroupMember.create(applyGroupData);
          //发送加入群聊的消息
          let applyGroupMessage={
              user_id:user_id,
              group_id:group_id,
              message:`${name}加入了群聊！`,
              time:new Date(),
              types:0
          }
          await this.app.model.GroupMessage.create(applyGroupMessage);
          return true
    }

    //退出群聊
    async deleteGroup(user_id,group_id){
        let groupmember=await this.app.model.GroupMember.findOne({where:{user_id:user_id,group_id:group_id}});
        let name=groupmember.name;
         await this.app.model.GroupMember.destroy({where:{user_id:user_id,group_id:group_id}});
         let deleteGroupMessage={
            user_id:user_id,
            group_id:group_id,
            message:`${name}退出了群聊！`,
            time:new Date(),
            types:0
         }
         await this.app.model.GroupMessage.create(deleteGroupMessage);
         return true
    }
}


module.exports = GroupService;